import Vue from 'vue'
import VueRouter from 'vue-router'
// import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import * as common from '@/common/common'
// import { getToken } from '@/api/user'

Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    redirect: '/welcome'
  },

  // 首页
  {
    path: '/welcome',
    name: 'Welcome',
    component: () => import('@/views/Home')
  },

  // 登陆注册页
  {
    path: '/lr',
    name: 'LR',
    component: () => import('@/views/LR/LR'),
    children: [
      {
        path: 'login',
        name: 'Login',
        component: () => import('@/views/LR/Login')
      },
      {
        path: 'register',
        name: 'Register',
        component: () => import('@/views/LR/Register')
      }
    ]
  },

  // 图书首页，展示多种图书
  {
    path: '/book',
    component: () => import('@/views/Book')
  },
  {
    path: '/book/:searchStr',
    component: () => import('@/views/Book')
  },
  {
    path: '/bookDetail/:id',
    component: () => import('@/views/BookDetail')
  },
  {
    path: '/profile',
    component: () => import('@/views/Profile'),
    meta: {
      needLogin: true
    }
  },
  // {
  //   path: '/profile/cart',
  //   component: () => import('@/views/Profile')
  // },
  {
    path: '/profile/:tabId',
    component: () => import('@/views/Profile'),
    meta: {
      needLogin: true
    }
  },
  // 订单详情
  {
    path: '/orderDetail/:id',
    component: () => import('@/views/OrderDetail'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/pay',
    component: () => import('@/views/Pay'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/404',
    component: () => import('@/views/error-page/404')
  },
  {
    path: '*',
    redirect: '/404'
  }
]

const router = new VueRouter({
  routes
})

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach((to, from, next) => {
  NProgress.start()
  // }
  if (to.meta.needLogin) {
    // 此路由需要先登陆
    // 判断本地是否有token和userInfo，有则跳转
    if (common.isExist('token') && common.isExist('userInfo')) {
      next()
    } else {
      Message.error('你还没有登陆，将跳转到登陆页面')
      setTimeout(() => {
        next(`/lr/login?redirect=${to.fullPath}`)
      }, 800)
    }
  } else {
    next()
  }
})

router.afterEach((to) => {
  // finish progress bar
  NProgress.done()
})

export default router
